/**
 * Copyright (C) 2012  The CFuture Android Ad-platform Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lurencun.android.support.ad.i;

import android.content.Context;
import android.os.Looper;

import com.lurencun.android.support.ad.AdSense;
import com.lurencun.android.support.ad.OnPayedListener;
import com.nd.dianjin.DianJinPlatform;
import com.nd.dianjin.DianJinPlatform.Oriention;
import com.nd.dianjin.webservice.WebServiceListener;

/**
 * 点金广告平台实现类
 * @author cfuture.chenyoca [桥下一粒砂] (chenyoca@163.com)
 * @date 2012-2-14
 */
public class DianJinAdSense extends AdSense {
	//cfuture.chenyoca MD5
	public static final String ORDER_SERIAL = "0576e8c45ef859507a33ddbc4e7ba859";
	public static final int ACTION_ID = 1008611;
	
	private static final String GET_BALANCE_NOT_ENOUGH = "余额不足！";
	private float mBalance = -1f;
	
	public DianJinAdSense(Context context,OnPayedListener listener,int appId,String appKey) {
		super(context,listener);
		DianJinPlatform.initialize(mContext, appId,appKey);
		this.startUpdate();
	}
	
	@Override
	protected final float updateBalances() {
		if(mBalance < 0f){
			new Thread(new Runnable(){
				@Override
				public void run() {
					Looper.prepare();
					DianJinPlatform.getBalance(mContext, new WebServiceListener<Float>() {
						@Override
						public void onResponse(int responseCode, Float balances) {
							if(responseCode == DianJinPlatform.DIANJIN_SUCCESS){
								mBalance = balances;
							}
						}
					});
					Looper.loop();
				}
			}).start();
		}
		return mBalance;
	}

	@Override
	protected final void doConsume(final int payGold) {
		DianJinPlatform.consume(mContext, ORDER_SERIAL, payGold, ACTION_ID,
			new WebServiceListener<Integer>() {
				@Override
				public void onResponse(int responseCode, Integer act) {
					if (DianJinPlatform.DIANJIN_SUCCESS == responseCode) {
						mPayListener.onPayedSuccess(payGold);
					} else if (DianJinPlatform.DIANJIN_ERROR_BALANCE_NO_ENOUGH == responseCode) {
						mPayListener.onPayedFailed(GET_BALANCE_NOT_ENOUGH);
						showOfferWall();
					}
				}
			});
	}

	@Override
	public final void showOfferWall() {
		DianJinPlatform.showOfferWall(mContext, Oriention.PORTRAIT);
	}

}
